package cn.lx.auth.secutity.filter;

import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import cn.lx.auth.secutity.utils.ApiVerifyUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName ApiAuthorizationFilter
 * @Description: //todo
 * @Author: 落雪
 * @CreateDate: 2025/7/14 23:21
 * @UpdateUser: 落雪
 * @UpdateDate: 2025/7/14 23:21
 * @UpdateRemark:
 * @Version: 1.0
 */
public class ApiAuthorizationFilter implements Filter {
    private static Logger log = LoggerFactory.getLogger(ApiAuthorizationFilter.class);

    public ApiAuthorizationFilter() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httprequest = (HttpServletRequest)request;
        HttpServletResponse httpresponse = (HttpServletResponse)response;
        ApiVerifyUtil apiVerifyUtil = new ApiVerifyUtil();

        try {
            if (apiVerifyUtil.whiteListVerify(httprequest.getServletPath().toString())) {
                chain.doFilter(request, response);
            } else if (apiVerifyUtil.access(httprequest)) {
                chain.doFilter(request, response);
            } else {
                log.info("callpath:" + httprequest.getServletPath().toString());
                httpresponse.setCharacterEncoding("UTF-8");
                httpresponse.setContentType("application/json; charset=utf-8");
                PrintWriter out = httpresponse.getWriter();
                JSONObject res = new JSONObject();
                res.put("code", 110001);
                res.put("type", WrapperResponse.ResponseType.TYPE_ERROR);
                res.put("message", "API没有访问权限!");
                res.put("data", "");
                out.append(res.toString());
                out.flush();
                out.close();
            }

        } catch (Exception var9) {
            log.error(var9.toString(), var9);
            throw var9;
        }
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void destroy() {
    }
}

